﻿using System;
using SAM.Framework.Security;
using SAM.Framework.ILicence;
using SAM.Framework.ILicence.Models;
using Newtonsoft.Json;

namespace SAM.Framework.LicenceGenerate
{
    public class LicenceEscapeService : ILicenceEscape, ILicenceUnescape
    {
        private readonly string secretKey = "SAM'LONG";
        private ISecurity security;

        public LicenceEscapeService(ISecurity security)
        {
            this.security = security;
        }

        public AuthorizationInfo Escape(MachineCodeInfo machineCodeInfo, LicenceInfo licenceInfo)
        {
            MachineTextCodeInfo machineTextCodeInfo = machineCodeInfo as MachineTextCodeInfo;
            AuthorizationNormInfo authorizationInfo = new AuthorizationNormInfo();
            string byteStr = JsonConvert.SerializeObject(licenceInfo);


            authorizationInfo.MachineCodeInfo = machineCodeInfo;
            authorizationInfo.AuthorizationCode = this.security.Escape(byteStr, secretKey);

            //与机器码异或

            return authorizationInfo;
        }

        public LicenceInfo Unescape(AuthorizationInfo authorizationInfo)
        {
            AuthorizationNormInfo info = authorizationInfo as AuthorizationNormInfo;
            string decode = this.security.Unescape(info.AuthorizationCode, secretKey);
            LicenceInfo licenceInfo = JsonConvert.DeserializeObject<LicenceInfo>(decode);
            return licenceInfo;
        }         
    }
}
